#!/usr/bin/env python

import os
import wx
import wx.lib.plot as plot
import numpy as numarray
import random
import sys
import wizard
import threading
import wx.lib.newevent
import time
import project
import wx.grid
import pickle
import shutil

from ga_settings_dialog import *
from ga_run_dialog import *

wildcard = "Project Files (*.proj)|*.proj|" \
    "All files (*.*)|*.*"

# Create a "NewGeneration" event - the event that the genetic algorithm generates
# on each iteration. By handling this event, the GUI is updated.
(NewGenerationEvent, EVT_NEW_GENERATION) = wx.lib.newevent.NewEvent()

# Create a "NewGA" event - the event that the project generates
# on each GA run. By handling this event, the GUI is updated.
(NewGAEvent, EVT_NEW_GA) = wx.lib.newevent.NewEvent()

# Create a "NewGA" event - the event that the project generates
# on each GA run. By handling this event, the GUI is updated.
(EndLongShotEvent, EVT_END_LS) = wx.lib.newevent.NewEvent()

class Current_Project(object):
    proj=None
    stat=None
    
    def __new__(type):      
    	if not '_the_instance' in type.__dict__:
    		type._the_instance = object.__new__(type)
    	return type._the_instance   
    
    
    def set_details_empty(self):
    	self.stat.txt_details.Clear()
    	self.proj=None
    	self.stat.proj=None
    	
    def set_current_project(self, projjy):
        self.proj=projjy
        if(self.stat!=None):
            self.stat.proj=projjy
            name=projjy.project_name.split("\\")[len(projjy.project_name.split("\\"))-1]
            tt=name+"\\"+name+"_config.txt"	
            self.stat.txt_details.Clear()
            self.stat.txt_details.LoadFile(tt, wx.TEXT_TYPE_ANY)


            if(len(self.proj.function.my_limits.keys())>1):
                if(self.stat.noteBook.PageCount!=3):
                    self.stat.noteBook.RemovePage(3)
                    self.stat.noteBook.Refresh()
            else:
                if(self.stat.noteBook.PageCount!=4):
                    self.stat.noteBook.AddPage(self.stat.pageFunctionTable, "Function chart", False)
                self.stat.data=(self.proj.function.create_function([]))[0]
                self.stat.function_chart.SetToolTip(wx.ToolTip("Shows the Function Graphic (Green)"+\
                                                               "and the Individuals of the population (Red)"))
                marker = plot.PolyLine(self.stat.data, legend='Function', colour='green')
                graph = plot.PlotGraphics([marker],self.proj.function.my_problem, "X Axis", "Function")
                self.stat.function_chart.Draw(graph)
                self.stat.noteBook.Refresh()
            

    def set_current_stats(self, statty):
    	self.stat=statty

class Application:
	def __init__(self):
		app = wx.App(False)
		frame = MainWindow()
		frame.Show()
		app.MainLoop()

class MyTreeCtrl(wx.TreeCtrl):
	def __init__(self, parent, id, pos, size, style):
		wx.TreeCtrl.__init__(self, parent, id, pos, size, style)

	def OnCompareItems(self, item1, item2):
		t1 = self.GetItemText(item1)
		t2 = self.GetItemText(item2)
		if t1 < t2: return -1
		if t1 == t2: return 0
		return 1

class TreeView(wx.Panel):
    def __init__(self, parent):
    	# Use the WANTS_CHARS style so the panel doesn't eat the Return key.
    	wx.Panel.__init__(self, parent, -1, style=wx.WANTS_CHARS)
    	self.Bind(wx.EVT_SIZE, self.OnSize)
    	
    	tID = wx.NewId()
    	
    	self.tree = MyTreeCtrl(self, tID, wx.DefaultPosition, wx.DefaultSize,
    			wx.TR_HAS_BUTTONS
    			| wx.TR_EDIT_LABELS
    			)
    	
    	isz = (16,16)
    	il = wx.ImageList(isz[0], isz[1])
    	fldridx     = il.Add(wx.ArtProvider_GetBitmap(wx.ART_FOLDER,      wx.ART_OTHER, isz))
    	fldropenidx = il.Add(wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN,   wx.ART_OTHER, isz))
    	fileidx     = il.Add(wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, isz))
    	#smileidx    = il.Add(images.getSmilesBitmap())
    	
    	self.tree.SetImageList(il)
    	self.il = il
    	
    	
    	self.root = self.tree.AddRoot("Projects In MathStorm")
    	self.tree.SetPyData(self.root, None)
    	self.tree.SetItemImage(self.root, fldridx, wx.TreeItemIcon_Normal)
    	self.tree.SetItemImage(self.root, fldropenidx, wx.TreeItemIcon_Expanded)
    
    	self.tree.Expand(self.root)
    	
    	self.tree.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)
    	self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, self.tree)
    
    def VerifyItem(self, name_to_verify):
    	cookie = 0
    	rt=self.tree.GetRootItem()
    	(child, cookie) = self.tree.GetFirstChild(rt)
    	
    	while child.IsOk():
    		name=self.tree.GetItemText(child)
    		if(name==name_to_verify):
    			return False
    		(child, cookie) = self.tree.GetNextChild(rt, cookie)
    	return True
     
    def AddItem(self, project_name, projecto):
    	isz = (16,16)
    	il = wx.ImageList(isz[0], isz[1])
    	fldridx     = il.Add(wx.ArtProvider_GetBitmap(wx.ART_FOLDER,      wx.ART_OTHER, isz))
    	fldropenidx = il.Add(wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN,   wx.ART_OTHER, isz))
    	fileidx     = il.Add(wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, isz))
    	
    	child = self.tree.AppendItem(self.root, project_name)
    	self.tree.SetPyData(child, projecto)
    	self.tree.SetItemImage(child, fldridx, wx.TreeItemIcon_Normal)
    	self.tree.SetItemImage(child, fldropenidx, wx.TreeItemIcon_Expanded)
    	
    	self.tree.Expand(self.root)
        
    def OnSize(self, event):
        w,h = self.GetClientSizeTuple()
        self.tree.SetDimensions(0, 0, w, h)
        
    def OnRightDown(self,event):
    
        pt = event.GetPosition();
        item, flags = self.tree.HitTest(pt)
        t=self.tree.GetItemData(item).GetData()
        text=self.tree.GetItemText(item)
        
        if(text=="Projects In MathStorm"):#IF is root
            pass
        else:
            if item:
                dialog = wx.MessageDialog(self, 
                   message="Do you want to remove the project "+t.project_name+"?",
                   style=wx.OK | wx.CANCEL
                   )   
            
                if dialog.ShowModal()==wx.ID_OK:
                    self.tree.Delete(item)
                    self.tree.Expand(self.root)
                    cp=Current_Project()
                    cp.set_details_empty()
                    
                    dialog2 = wx.MessageDialog(self, 
                       message="Do you want to remove the project from the disk?",
                       style=wx.OK | wx.CANCEL
                       )   
                
                    if dialog2.ShowModal()==wx.ID_OK:
                       remove_dir = os.getcwd()+"\\"+self.tree.GetItemText(item)
                       shutil.rmtree(remove_dir)

                    dialog2.Destroy()
                        
                dialog.Destroy()

    def OnSelChanged(self, event):
    	self.item = event.GetItem()
    	t=self.tree.GetItemText(self.item)
    	if(t!="Projects In MathStorm"):            
            p=self.tree.GetItemData(self.item).GetData()
            cp=Current_Project()
            cp.set_current_project(p)
            self.data = []
            self.dudes = []

class AGRunnerThread(threading.Thread):

    def __init__(self, mainWindow):
	    threading.Thread.__init__(self)
	    self.mainWindow = mainWindow
            
    def run(self):
       cp = Current_Project()
       if(cp.proj!=None):
           cp.proj.start_runs(self.mainWindow,NewGenerationEvent,\
                              NewGAEvent, EndLongShotEvent)

class MainWindow(wx.Frame):
    """Program Start Window"""
    
    def __init__(self):
    	
    	self.proj=None
    
    	cp=Current_Project()
    	cp.set_current_stats(self)
    
    	self.HEIGHT = 500
    	self.WIDTH = 700
    	
    	## window stuf
    	wx.Frame.__init__(self, None, size=(self.WIDTH,self.HEIGHT), title='Math Storm')
    	#	self.SetIcon(wx.Icon(self.GetIcon('simulator'), wx.BITMAP_TYPE_PNG))
    	self.Center()
    
        self.Bind(wx.EVT_CLOSE , self.OnExit)
        ## GUI stuf
    	self.MakeMenuBar()
    	self.MakeToolBar()
    	self.MakeStatusBar()
    	   	
    	## info stuf
    	self.DivideWindow()
    	self.FillPanelUp()
    	self.FillPanelDown()
    	self.FillPanelLeft()
        self.Load_projects()
    
    def load_proj(self,file_name):
        os.chdir(os.getcwd()+"\\"+file_name)
        newproj=project.Project()
        newproj.load_project(file_name+"_config.proj")
        if(self.tree.VerifyItem(newproj.project_name)):
            self.tree.AddItem(newproj.project_name, newproj)
        
    def Load_projects(self):
        file_save = file("save_proj.dat","r")
        list_save=pickle.load(file_save)
        for i in list_save:
            self.load_proj(i)
    
    def DivideWindow(self):
    	"""Divides the initial frame in 3 panels"""
    
    	vertical_splitter = wx.SplitterWindow(self) #spliter in the frame		
    	vertical_splitter.SetMinimumPaneSize(175)
    
    	self.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGING, self.OnVerticalSashChanging, vertical_splitter)
    
    	horizontal_splitter = wx.SplitterWindow(vertical_splitter, style=wx.SP_LIVE_UPDATE) #spliter in the spliter frame
    	horizontal_splitter.SetSashGravity(0.5)
    	horizontal_splitter.SetMinimumPaneSize(100)
    
    	self.panel_left = wx.Panel(vertical_splitter, style=wx.SUNKEN_BORDER) #left panel in vSplit
    	self.panel_up = wx.Panel(horizontal_splitter, style=wx.SUNKEN_BORDER) #up panel in hSplit
    	self.panel_down = wx.Panel(horizontal_splitter, style=wx.SUNKEN_BORDER) #down pane in hSplit
    	
    	vertical_splitter.SplitVertically(self.panel_left, horizontal_splitter, self.GetClientSize()[0] / 4) #slit the vertical frame
    	horizontal_splitter.SplitHorizontally(self.panel_up, self.panel_down, self.GetClientSize()[1] / 2) #slit the horizontal frame
    
    	
    def MakeMenuBar(self):
    	data = (("&File",
    		 ('&New...\tCtrl+N', 'Create a new project','new', self.OnNewProject),
    		 ('&Open...\tCtrl+O', 'Open an existing project','open', self.OnOpenProject),
    		 ('','','',''),
    		 ('&Quit\tCtrl+Q', 'Terminate the application',None,self.OnExit)
    		 ),
    	        ('&Tools',
    		 ('&Run', 'Runs the current GA',None, self.OnRun),
    		 ('&Config', 'Changes the settings of the current GA',None, self.OnConfig)
    		 ), 
    	        ('&About',
    		 ('&About', 'Info about the program',None,self.OnAbout)
    		 ))
    
    	def createMenu(menuData):
    		menu = wx.Menu()
    		for eachLabel, eachStatus,eachImage, eachHandler in menuData:
    			if not eachLabel:
    				menu.AppendSeparator()
    				continue
    			menuItem = menu.Append(-1, eachLabel, eachStatus)
    			if eachImage != None:
    				menuItem.SetBitmap(self.GetIcon(eachImage))
    				self.Bind(wx.EVT_MENU, eachHandler, menuItem)
    
    		return menu
    	
    	menuBar = wx.MenuBar()
    	for eachMenuData in data:
    		menuLabel = eachMenuData[0]
    		menuItems = eachMenuData[1:]
    		menuBar.Append(createMenu(menuItems), menuLabel)
    		self.SetMenuBar(menuBar)
    
 
    def MakeToolBar(self):
    	
    	def ProcessIcons(window, data):
    		toolbar = window.CreateToolBar()
    		toolbar.SetToolBitmapSize((24,24))
    		for each in data:
    			MakeToolBarItem(window, toolbar, *each)
    		toolbar.Realize()
    	
    	def MakeToolBarItem(window, toolbar, label, icon, help, handler):
    		if label=="": #not label
    			toolbar.AddSeparator()
    		else:
    			tool = toolbar.AddSimpleTool(-1, icon, label, help)
    			window.Bind(wx.EVT_MENU, handler, tool)
    	
    	data = (("New", self.GetIcon('new'), "Makes a new project", self.OnNewProject),
    		("Open", self.GetIcon('open'), "Opens a new project", self.OnOpenProject),
    		("", "", "", ""),
    		("Run", self.GetIcon('run'), "Runs the current GA", self.OnRun),
    		("Config", self.GetIcon('config'), "Changes the settings of the current GA", self.OnConfig),
    		("", "", "", ""),
    		("Exit", self.GetIcon('exit'), "Closes the stuf", self.OnExit))
    	
    	ProcessIcons(self, data)
    
    
    def MakeStatusBar(self):
    	statusBar = self.CreateStatusBar()
    	statusBar.SetFieldsCount(2)
    	statusBar.SetStatusWidths([-3, -1])
    
    
    def GetIcon(self,name):
    	icon_path = 'imgs/'
    	icon_dict = { 'simulator':	'preferences-desktop-sound.png', #icon da janela
    		      ### File 
    		      'new':		'document-new.png',
    		      'open':		'document-open.png',
    		      'save':		'document-save.png',
    		      'save_as':		'document-save-as.png',
    		      ### Config
    		      'run':		'media-playback-start.png',
    		      'config':		'stock_chart-edit-type.png',
    		      ### Other
    		      'exit':		'system-log-out.png'
    		      }
    
    	return wx.Bitmap(icon_path + icon_dict[name], wx.BITMAP_TYPE_PNG)

    def FillPanelDown(self):
                
        def MakeFunctionDetails(notebook):
            
			pageStats = wx.Panel(self.noteBook, -1)
	
			sizer = wx.BoxSizer(wx.VERTICAL)
			pageStats.SetSizer(sizer)
			
			
			self.txt_details = t3 = wx.TextCtrl(pageStats, -1,
			            "",
			            style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER)
			self.txt_details.SetEditable(False)
			sizer.Add(self.txt_details, 1, wx.EXPAND)
			return pageStats
            
    
    	def MakeGenerationsTable(noteBook):
            columns = (("Gen.", 50) , ("Best fitness", 100), ("Avg. fitness", 100), ("Standard deviantion", 150))
            
            
            pageGenerations = wx.Panel(self.noteBook, -1)
            
            sizer = wx.BoxSizer(wx.VERTICAL)
            pageGenerations.SetSizer(sizer)
            
            colLabels = ["Best fitness", "Average Fitness", "Standard Deviation"]
                       
            self.GenerationsGrid=wx.grid.Grid(pageGenerations)    		
            self.GenerationsGrid.CreateGrid(0, 3)
            
            for column in range(len(colLabels)):
                self.GenerationsGrid.SetColSize(column, 150)
                self.GenerationsGrid.SetColLabelValue(column, colLabels[column])
            
            sizer.Add(self.GenerationsGrid, 1, wx.EXPAND)
            
            return pageGenerations
    
    
    	def MakeFunctionChart(noteBook):
    		self.pageFunctionTable = wx.Panel(self.noteBook, -1)
    
    		sizer = wx.BoxSizer(wx.VERTICAL)
    		self.pageFunctionTable.SetSizer(sizer)
    
    		self.function_chart = plot.PlotCanvas(self.pageFunctionTable)
    		sizer.Add(self.function_chart, 1, wx.EXPAND)

    		return self.pageFunctionTable
  
        def MakeRunsTable(noteBook):
            columns = ["Fitness (Avg)", "Average (Avg)" , "Number of Runs", "Population", "Arity", "Contestants", "Loosers Hype", 
                       "Crossover Rate","Cut Points", "Alpha","Mutation Rate","Elitism"]
            
            self.pageRuns = wx.Panel(self.noteBook, -1)
            
            sizer = wx.BoxSizer(wx.VERTICAL)
            self.pageRuns.SetSizer(sizer)

            self.RunsGrid=wx.grid.Grid(self.pageRuns)            
            self.RunsGrid.CreateGrid(0, len(columns))
            
            for column in range(len(columns)):
                self.RunsGrid.SetColSize(column, 100)
                self.RunsGrid.SetColLabelValue(column, columns[column])
            
            sizer.Add(self.RunsGrid, 1, wx.EXPAND)
            
            return self.pageRuns
    
    
    	sizer = wx.BoxSizer(wx.VERTICAL)
    	self.panel_down.SetSizer(sizer)
    	
    	self.noteBook = wx.Notebook(self.panel_down, -1)
        self.noteBook.AddPage(MakeFunctionDetails(self.noteBook), "Project Details", False)
    	self.noteBook.AddPage(MakeGenerationsTable(self.noteBook), "Generations", False)
        self.noteBook.AddPage(MakeRunsTable(self.noteBook), "Project Runs", False)
    	self.noteBook.AddPage(MakeFunctionChart(self.noteBook), "Function chart", False)
           
    	sizer.Add(self.noteBook, 1, wx.EXPAND)
    
    	self.Bind(EVT_NEW_GENERATION, self.OnNewGeneration)
        self.Bind(EVT_NEW_GA , self.OnNewGA)
        self.Bind(EVT_END_LS , self.OnLongShotEnd)
        
    def FillPanelUp(self):
    	"""
    	Fills the upper-right panel
    	"""
    
    	sizer = wx.BoxSizer(wx.VERTICAL)
    	self.panel_up.SetSizer(sizer)
    
    	self.ga_chart = plot.PlotCanvas(self.panel_up)
    	sizer.Add(self.ga_chart, 1, wx.EXPAND)

    	self.ga_chart_data = []
    	self.ga_mean_data = []
        
    def FillPanelLeft(self):
        
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.panel_left.SetSizer(sizer)
        
        self.tree=TreeView(self.panel_left)
        
        sizer.Add(self.tree, 1, wx.EXPAND)

    def on_update_project(self):
        
        cp=Current_Project()
        self.proj=cp.proj

    def removeAllGenerationData(self):
        #self.GenerationsGrid.ClearGrid()
        if(self.GenerationsGrid.GetNumberRows()>0):
            self.GenerationsGrid.DeleteRows(0, self.GenerationsGrid.GetNumberRows())
            
    def removeAllLongShotData(self):
        #self.GenerationsGrid.ClearGrid()
        if(self.RunsGrid.GetNumberRows()>0):
            self.RunsGrid.DeleteRows(0, self.RunsGrid.GetNumberRows())
    
    def addGenerationData(self, generation, *par_list):

    	self.GenerationsGrid.AppendRows(1)
    	self.GenerationsGrid.SetRowLabelValue(generation-1, "Gener. "+str(generation))
        
    	#Best One
    	self.GenerationsGrid.SetCellValue(generation-1,0, str(par_list[0]))
    	#Average
    	self.GenerationsGrid.SetCellValue(generation-1,1, str(par_list[1]))
        #Standard Deviation
        self.GenerationsGrid.SetCellValue(generation-1,2, str(par_list[2]))
        
    	self.GenerationsGrid.Refresh()
        
    def addRunData(self, agNumber, par_list):
        
        self.RunsGrid.AppendRows(1)
        self.RunsGrid.SetRowLabelValue(agNumber, "AG Numero "+str(agNumber))
        
        for i in range(0, 12):
            if((i==0)|(i==1)):
                self.RunsGrid.SetCellValue(agNumber,i, str(float(par_list[i])/float(par_list[2])))
            else:
                self.RunsGrid.SetCellValue(agNumber,i, str(par_list[i]))
        
    

    def OnNewProject(self,event):
        proj=wizard.beginWizard()
        if proj != None :
        	os.chdir(os.getcwd()+"\\"+proj)
        	newproj=project.Project()
        	newproj.load_project(proj+"_config.proj")   
        	self.tree.AddItem(newproj.project_name, newproj)


    def OnOpenProject(self,event):
        
        self.ga_chart_data = []
    	self.ga_mean_data = []
        
        dialog = wx.FileDialog(self, 
               message="Choose a file",
               defaultDir=os.getcwd(), 
               defaultFile="",
               wildcard=wildcard,
               style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR
               )   
        
        if dialog.ShowModal()==wx.ID_OK:
            project_name = dialog.GetPath() 
            newproj=project.Project()
            newproj.load_project(project_name)
            if(self.tree.VerifyItem(newproj.project_name)):
             	self.tree.AddItem(newproj.project_name, newproj)
            else:
            	dialog2 = wx.MessageDialog(self, 'Project Already Loaded','Problem', wx.OK)
            	dialog2.ShowModal()
            	dialog2.Destroy()
            	
        dialog.Destroy()
    
    def OnSave(self,event):
        #page=self.noteBook.GetPage(3)
        self.removeAllGenerationData()
        
    
    def OnSaveAs(self,event):
    	
    	dialog = wx.FileDialog(self, 
    			       message="Save file as ...", 
    			       defaultDir=os.getcwd(), 
    			       defaultFile="", 
    			       wildcard=wildcard, 
    			       style=wx.SAVE
    			       )
    	if dialog.ShowModal() == wx.ID_OK:
    		path =dialog.GetPath()
    		fp=file(path, 'w')
    		fp.write('TESTE')
    		fp.close()
    		
    	dialog.Destroy()
    
    def OnRun(self,event):
        self.ga_chart_data=[]
        self.ga_chart.SetToolTip(wx.ToolTip("Shows the evolution of the Best Individual' fitness (blue),\n"+\
                                 "and the mean of the populations's fitness (red),\n"+\
                                 "throughout the GA's generations"))	

    	thread = AGRunnerThread(self)
    	thread.start()
    	
    	self.ga_chart_data = []
    	self.ga_mean_data = []
        self.removeAllLongShotData()
    
    def OnConfig(self, event):
		dialog = GASettingsDialog(self.proj)
		dialog.ShowModal()
		dialog.Destroy()
    
    def OnAbout(self, event):
    	dialog = wx.MessageDialog(self, 'Computacao Evolucionaria\nJanuary \'07', 'About', wx.OK)
    	dialog.SetIcon(wx.Icon(GetIcon('about'), wx.BITMAP_TYPE_PNG))
    	dialog.ShowModal()
    	dialog.Destroy()
    
    def OnExit(self, event):
        ###CHANGE
        list_save=[]
        root=self.tree.tree.GetRootItem()
        (child, cookie) = self.tree.tree.GetFirstChild(root)
        while child.IsOk():
            list_save.append(self.tree.tree.GetItemText(child))
            (child, cookie) = self.tree.tree.GetNextChild(root,cookie)
        
        file_save = file("save_proj.dat","w")
        pickle.dump(list_save,file_save)
        sys.exit(0)
    	
    def OnVerticalSashChanging(self, event):
    	"""Prevents the vertical splitter front being moved"""
    	event.SetSashPosition(-1)
    
    def OnLongShotEnd(self, event):
        self.ga_chart_data = []
        self.ga_mean_data = []
        
        for i in range(0, len(event.results)):
            self.ga_chart_data += [[i, event.results[i][0].best().get_fitness()]]
            self.ga_mean_data +=  [[i, event.results[i][0].average()]]
            
        marker = plot.PolyLine(self.ga_chart_data, legend='Cross Legend', colour='blue')        
        marker2 = plot.PolyLine(self.ga_mean_data, legend='Cross Legend', colour='red')    
        graph = plot.PlotGraphics([marker, marker2],"Longshot Evolution", "GA num", "Fitness")
        self.ga_chart.SetToolTip(wx.ToolTip("Shows the evolution of the Best Individual's fitness (blue),\n"+\
                                 "and the mean of the populations's fitness(red),\n"+\
                                 "throughout each GA run.\n"))
        self.ga_chart.Draw(graph)
        
    
    def OnNewGA(self, event):
        self.addRunData(event.iter, event.par_list)
        self.ga_chart_data = []
        self.ga_mean_data = []
        
    
    def OnNewGeneration(self, event):
            
        if(event.generation!=0):
            self.addGenerationData(event.generation, event.best, event.avg, event.stdev)
        else:
            self.removeAllGenerationData()
            self.ga_chart_data = []
            self.ga_mean_data = []
            
    	#Draws Statistics
    	self.ga_chart_data += [[event.generation, event.best]]
     	self.ga_mean_data += [[event.generation, event.avg]]
    	marker = plot.PolyLine(self.ga_chart_data, legend='Cross Legend', colour='blue')		
    	marker2 = plot.PolyLine(self.ga_mean_data, legend='Cross Legend', colour='red')	
    	graph = plot.PlotGraphics([marker, marker2],"GA's evolution", "Generation", "Fitness")
    	self.ga_chart.Draw(graph)
    	
    	#Draws Function
    	[self.data, self.dudes]=(self.proj.function.create_function(event.pop))
        if(self.data!=None):
        	marker = plot.PolyLine(self.data, legend='Function', colour='green')
        	marker2 = plot.PolyMarker(self.dudes, legend='Individuals', colour='red', marker='circle',size=1)
         	graph = plot.PlotGraphics([marker, marker2],self.proj.function.my_problem, "X Axis", "Function")
        	self.function_chart.Draw(graph)

if __name__ == "__main__":
	Application()

